import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {NbToastStatus} from '@nebular/theme/components/toastr/model';
import {Block} from '../../service/peer.service';
import {PeerService} from '../../service/peer.service';
import {NbToastrService} from '@nebular/theme';

@Component({
  selector: 'app-peer-add',
  templateUrl: './peer-add.component.html',
  styleUrls: ['./peer-add.component.css']
})
export class PeerAddComponent implements OnInit {
  ip: string;
  port: string;
  isTest: boolean;
  constructor(private http: HttpClient,
              private peerService: PeerService,
              private toastrService: NbToastrService) {
    this.isTest = true;
  }

  ngOnInit() {
  }

  testPeer() {
    if (this.ip && this.port) {
      this.peerService.testPeer(this.ip, this.port).subscribe(
        (data: Block) => {
          this.isTest = false;
          this.toastrService.show('节点已设置', this.ip + ':' + this.port, {status: NbToastStatus.SUCCESS});
        },
        (error) => {
          this.toastrService.show(error.name, '节点未设置', {status: NbToastStatus.DANGER});
        }
      );
    }
  }

  addPeer() {
    if (this.ip && this.port) {
      this.peerService.addPeer(this.ip, this.port).subscribe(
        (data) => {
          if (data === 'success') {
            this.toastrService.show('添加成功', this.ip + ':' + this.port, {status: NbToastStatus.SUCCESS});
          }
        },
        (error) => {
          this.toastrService.show(error.name, '添加失败', {status: NbToastStatus.DANGER});
        }
      );
    }
  }

}
